package com.yugao.fintech.draper.datascope.config;

import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.yugao.fintech.draper.datascope.aspect.DataScopeAnnotationAdvisor;
import com.yugao.fintech.draper.datascope.interceptor.DataScopeInterceptor;
import com.yugao.fintech.draper.datascope.strategy.DataScopeStrategyConfiguration;
import com.yugao.fintech.draper.datascope.strategy.DepartmentDataScopeService;
import com.yugao.fintech.draper.datascope.strategy.DepartmentDataScopeStrategy;
import com.yugao.fintech.draper.datascope.strategy.factory.DataScopeStrategyFactory;
import com.yugao.fintech.draper.datascope.strategy.factory.DefaultDataScopeStrategyFactory;
import com.yugao.fintech.draper.datascope.strategy.DataScopeStrategy;
import com.yugao.fintech.draper.datasource.utils.MyBatisUtils;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.context.annotation.Bean;

import java.util.List;

/**
 * 数据权限的自动配置类
 */
@AutoConfiguration
public class DataScopeAutoConfiguration {
    /**
     * 注入数据权限规则工厂
     *
     * @param strategies 容器中的数据权限规则类
     */
    @Bean
    public DataScopeStrategyFactory dataPermissionRuleFactory(List<DataScopeStrategy> strategies) {
        return new DefaultDataScopeStrategyFactory(strategies);
    }

    /**
     * 添加拦截器 重写sql
     */
    @Bean
    public DataScopeInterceptor dataScopeInterceptor(MybatisPlusInterceptor interceptor, List<DataScopeStrategy> rules) {
        // 数据权限规则工厂接口
        DataScopeStrategyFactory ruleFactory = dataPermissionRuleFactory(rules);
        // 创建 DataPermissionDatabaseInterceptor 拦截器
        DataScopeInterceptor inner = new DataScopeInterceptor(ruleFactory);
        // 需要加在分页插件前面
        MyBatisUtils.addInterceptor(interceptor, inner, 0);
        return inner;
    }

	/**
	 * 构建部门数据权限规则对象
	 * @param service 数据权限service对象
	 * @param customizers 容器中自定义的部门数据权限规则集合
	 * @return 数据权限对象
	 */
	@Bean
	public DepartmentDataScopeStrategy deptDataPermissionRule(DepartmentDataScopeService service, List<DataScopeStrategyConfiguration> customizers) {
		// 创建数据权限规则对象
		DepartmentDataScopeStrategy rule = new DepartmentDataScopeStrategy(service);
		// 根据配置的自定义规则 补全部门数据权限的表信息
		customizers.forEach(customizer -> customizer.customize(rule));
		return rule;
	}

    /**
     * 数据权限aop处理
     */
    @Bean
    public DataScopeAnnotationAdvisor dataScopeAnnotationAdvisor() {
        return new DataScopeAnnotationAdvisor();
    }
}
